package com.itheima04;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class ReflectDemo1 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<?> c = Class.forName("com.itheima02.Student");

        // 公共的成员变量
        Field[] field = c.getFields();
        for (Field f : field) {
            System.out.println(f);
        }
        System.out.println("------");

        // 全部成员变量
        Field[] declaredFields = c.getDeclaredFields();
        for (Field f : declaredFields) {
            System.out.println(f);
        }
        System.out.println("------");

        // 获取单个公共成员变量
        Field address = c.getField("address");

        // 获取无参构造方法，创建对象
        Constructor<?> constructor = c.getConstructor();
        Object o = constructor.newInstance();

        // 给对象的 address 属性赋值
        address.set(o, "西安");

        System.out.println(o);

    }
}
